package com.solcoo.merchant.ui.order;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.android.common.util.StringUtil;
import com.android.common.view.OnPullListener;
import com.android.common.view.PullListView;
import com.solcoo.merchant.ApplicationExt;
import com.solcoo.merchant.Constant;
import com.solcoo.merchant.R;
import com.solcoo.merchant.base.BaseActivity;
import com.solcoo.merchant.base.task.TaskHelper;
import com.solcoo.merchant.base.task.TaskHelper.Callback;
import com.solcoo.merchant.base.task.TaskHelper.DefaultCallback;
import com.solcoo.merchant.model.OrderListDO;

public class OrderActivity extends BaseActivity implements
		OnPullListener<OrderListDO> {

	OrderAdapter adapter;

	PullListView orderList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order);
		orderList = (PullListView) findViewById(R.id.order_list);
		adapter = new OrderAdapter(this);
		orderList.setAdapter(adapter);
		orderList.setOnPullListener(this);
		TaskHelper.loadView(this, Constant.URL.getOrderList(
				ApplicationExt.getUser().yonghum, adapter.cursor), callback,
				OrderListDO.class);
	}

	private Callback<OrderListDO> callback = new DefaultCallback<OrderListDO>(
			this) {

		@Override
		public void onSuccess(OrderListDO result) {
			adapter.update(result);
			orderList.setVisibility(View.VISIBLE);
			orderList.setSelection(1);
			if (!adapter.hasMore()) {
				orderList.setFooterViewVisibility(View.GONE);
			}
			initHead(result);
		}
	};

	private void initHead(OrderListDO result) {
		TextView payTotal = (TextView) findViewById(R.id.pay_total);
		TextView recharge = (TextView) findViewById(R.id.recharge_total);
		payTotal.setText(result.zxiaofei);
		recharge.setText(result.zchongzhi);
	}

	@Override
	public OrderListDO onTopRefreshingInBackground() {
		adapter.cursor = 0;
		return TaskHelper.syncGet(Constant.URL.getOrderList(
				ApplicationExt.getUser().yonghum, adapter.cursor),
				OrderListDO.class);
	}

	@Override
	public String onTopRefreshed(OrderListDO result) {
		adapter.update(result);
		if (!adapter.hasMore()) {
			orderList.setFooterViewVisibility(View.GONE);
			return getString(R.string.pull_list_footer_no_more_toast_msg);
		}
		return StringUtil.EMPTY;
	}

	@Override
	public OrderListDO onBottomLoadingInBackground() {
		return TaskHelper.syncGet(Constant.URL.getOrderList(
				ApplicationExt.getUser().yonghum, adapter.cursor),
				OrderListDO.class);
	}

	@Override
	public String onBottomLoaded(OrderListDO result) {
		adapter.add(result);
		if (!adapter.hasMore()) {
			orderList.setFooterViewVisibility(View.GONE);
			return getString(R.string.pull_list_footer_no_more_toast_msg);
		}
		return StringUtil.EMPTY;
	}
}
